let selectCityCode = '', selectCityName = '', my = null,btnEditClickNum = 0,
    zeroArr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],nowYear = new Date().getFullYear() + '',
    monthArr = ['01', '02', '03', '04', '05', '06', '07','08', '09', '10', '11', '12'],
    allProvince = '110000,北京;120000,天津;130000,河北;140000,山西;150000,内蒙古;210000,辽宁;220000,吉林;230000,黑龙江;310000,上海;320000,江苏;330000,浙江;340000,安徽;350000,福建;360000,江西;370000,山东;410000,河南;420000,湖北;430000,湖南;440000,广东;450000,广西;460000,海南;500000,重庆;510000,四川;520000,贵州;530000,云南;540000,西藏;610000,陕西;620000,甘肃;630000,青海;640000,宁夏;650000,新疆;710000,台湾;810000,香港;820000,澳门',
    provinceArray = allProvince.split(';'),currentPage = 1, pageSize = 9,ventTotalPage = 0,
    checkCodeInterval, nowDate = new Date();
let month = nowDate.getMonth() + 1;
month = month < 10 ? '0' + month : month;
let yearMonth = nowDate.getFullYear() + '' + month;
$(function() {
    initMyInfo();
	//编辑按钮
	$('.btn-edit').click(function () {
        //编辑按钮点击次数，如果是第一次点击，则将my信息赋值给编辑里的字段值
	    btnEditClickNum ++;
	    $('.edit-phone').hide();
		editMyInfo();
    });
	//保存按钮
	$('.btn-group .btn').click(function () {
	    let btnId = $(this).attr('id');
	    if (btnId == 'btnSaveMyInfo'){
            saveMyInfo();
            return;
        }
        cancelEdit();
	});
	//修改手机号
	$('.edit-phone').click(function () {
	    let btnText = $(this).text(),ep = $('.ep'),epDown = $('.ep-down');
	    if (btnText == '修改'){
            ep.show();
            epDown.hide();
            $(this).text('取消');
        } else {
            resetEditPhone();
        }
    });
	//获取验证码
	let btnGetCode = $('#btnGetCheckCode');
    btnGetCode.click(function () {
        this.disabled = true;
        let time = 60;//60秒倒计时
        checkCodeInterval = window.setInterval(function () {
            time --;
            if (time < 1) {
                setGetCheckCodeEnable();
            }else {
                btnGetCode.text(time + '秒后获取');
            }
        },1000);
        goGetCheckCode();
    });
    //修改绑定手机号
    $('#submitNewPhone').click(function() {
        this.disabled = true;
        modifyMyPhone();
    });
	$('.center').mouseover(function () {
		$('.mark').show();
	}).mouseout(function () {
		$('.mark').hide();
	});
	$('.menu').click(function () {
        $('.menu').removeClass('selected');
        $(this).addClass('selected');
        let divClass = $(this).attr('divClass');
        $('.data,.navigation').hide();
        $('.' + divClass).show();
        if (divClass == 'my-vent'){
            listMyVent(currentPage,pageSize);
        }else {
            loadAllChart();
        }
    });
    let proList = $('.province-list'), cityList = $('.city-list');
	$('.choose-province').click(function () {
        //如果省份下拉框是显示的，则隐藏，隐藏的则显示
        showMeHideOther(proList);
    });
    $('.choose-city').click(function () {
        showMeHideOther(cityList);
    });
    $('.choose-year,.choose-month,.choose-day').click(function () {
        showMeHideOther($('#' + $(this).attr('showId')).parent());
    });
	let bodyWidth = $('body').width();
	//设置统计图的宽度
	$('.chart').css('width', bodyWidth * 0.8 * 0.48);
	let href = location.href;
	if (href.indexOf('?') > 0){
	    href = href.split('?')[1];
	    //如果是查看我的吐槽
	    if (href == 'mv'){
	        $('.menu-list .selected').removeClass('selected');
	        $('#btnMyVent').addClass('selected');
	        $('.chart-list').hide();
	        $('#myVentList,.navigation').show();
            listMyVent(currentPage,pageSize);
            return;
        }
    }
    loadAllChart();
	$('#uploadHeaderImg').click(function () {
        $('#uploadImg').click();
    });
});
function resetEditPhone() {
    $('.ep').hide();
    $('.ep-down').show();
    $('.edit-phone').text('修改');
}
/**
 * 加载所有的统计图
 */
function loadAllChart() {
    //如果已加载过了，则不再加载
    if ($('.chart-list .chart').children().length > 1){
        return;
    }
    loadHomePageLookNum();
    loadAccessSiteNum();
    loadIssueVentNum();
    loadLikeVentNum();
}
/**
 * 显示当前对象，隐藏其它下拉框
 * @param o
 */
function showMeHideOther(o) {
    //如果省份下拉框是显示的，则隐藏，隐藏的则显示
    if(isHide(o)){
        $('.choose-list').hide();
        o.show();
    }else {
        o.hide();
    }
}
/**
 * 是否隐藏
 * @param o jquery对象$('')
 * @returns {boolean} true:隐藏，false:显示
 */
function isHide(o) {
    return o.css('display') == 'none';
}
/**
 * 初始化我的信息
 */
function initMyInfo() {
    $.ajax({
        type: 'post',
        url : '/ventUserIndex/getMyInfo',
        dataType: 'json',
        async: false,
        timeout: 12000,
        success: function (myData) {
            if (myData.status == -1){
                alert('登录失效，请重新登录');
                setLogin();
                return;
            }
            my = myData.my;
            setInfo(my);
            let b = my.birthday;
            if (!isNull(b)){
                $('#seeBirthday').text(b.substring(0,2) + '**年');
            }
            $('title,header h3').text('我的主页');
            setMyHeaderImg(my.headerImgPath);
        },
        error: function () {
            alert("获取我的信息失败，请稍候再试");
        }
    });
}
function setLogin() {
    sessionStorage.setItem('backUrl','myHome');
    location.href = 'ventLogin.html';
}
/**
 * 编码我的信息
 */
function editMyInfo() {
    $('header .left,header .right').css('width','386px');
    $('.btn-edit,.see').hide();
    $('.btn-group .btn,.edit').show();
    let nickNameV = $('#nickName').val();
    $('#nickName').val(isNull(nickNameV) ? $('#seeNickName').text() : nickNameV);
    $('#phone').val($('#seePhone').text());
    let emailV = $('#email').val();
    $('#email').val(isNull(emailV) ? $('#seeEmail').text() : emailV);
    if($('#yearList').children().length < 1){
        setDate();
    }
    let sexV = $('#seeSex').text();
    $('#sex').attr('checked',sexV == '女');
    let pl = $('#provinceList');
    if(pl.children().length < 1) {
        let provinceArr = [];
        for (let g = 0; g < provinceArray.length; g ++) {
            let pCodeName = provinceArray[g].split(',');
            provinceArr.push('<span class="province-obj choose-obj" id="' + pCodeName[0] + '">' + pCodeName[1] + '</span>');
        }
        pl.append(provinceArr.join(''));
    }
    $('.province-obj').click(function (e) {
        $(".province-list").hide();
        $('#showProvince').text(this.innerText);
        $('#showCity').text('城市');
        e.stopPropagation();
        let cityList = listCityByProvince(this.id);
        let cityListLen = cityList.length, cityArr = [];
        for (let g = 0; g < cityListLen; g ++){
            let cityObj = cityList[g];
            cityArr.push('<span class="choose-obj city-obj" id="' + cityObj.cityCode + '">' + cityObj.cityName + '</span>');
        }
        $('#listCity').empty().append(cityArr.join(''));
        $('.city-obj').click(function (e) {
            selectCityCode = this.id;
            selectCityName = this.innerHTML;
            $(this).parent().parent().hide();
            $('#showCity').text($(this).text());
            $('.city-list').hide();
            e.stopPropagation();
        });
    });

    let occupationArr = [];
    getDictionaries(52,true,function (occupationList) {
        for (let b = 0; b < occupationList.length; b ++){
            let o = occupationList[b];
            occupationArr.push('<option value="' + o.id + '">' + o.dicName + '</option>');
        }
        $('#occupationName').append(occupationArr.join(''));
    });
    //如果不是第一次点击编辑按钮
    if (btnEditClickNum > 1){
        return;
    }
    let b = my.birthday,provinceCode = my.atProvinceCode,
        bloodType = my.bloodType,occupationId = my.occupationId;
    if (!isNull(b)){
        let ymrArr = b.split('-');
        $('#showYear').text(ymrArr[0]);
        $('#showMonth').text(ymrArr[1]);
        $('#showDay').text(ymrArr[2]);
    }
    if (!isNull(provinceCode)){
        for (let g = 0; g < provinceArray.length; g ++) {
            let pCodeName = provinceArray[g].split(',');
            if (provinceCode == pCodeName[0]){
                $('#showProvince').text(pCodeName[1]);
                break;
            }
        }
        $('#showCity').text(my.atCityName);
    }
    if (!isNull(bloodType)){
        $('#bloodType').val(bloodType == '其它' ? 'T' : bloodType);
    }
    if (!isNull(occupationId)){
        $('#occupationName').val(occupationId);
    }
}

/**
 * 设置年月日日期
 */
function setDate() {
    let now = new Date();
    let maxYear = now.getFullYear() - 10,yearArr = [],monthArr = [];
    for (let y = maxYear; y > 1949; y --){
        yearArr.push('<span class="choose-obj year-obj">' + y + '</span>');
    }
    $('#yearList').append(yearArr.join(''));
    for (let m = 1; m < 13; m ++){
        monthArr.push('<span class="choose-obj month-obj">' + m + '</span>');
    }
    $('#monthList').append(monthArr.join(''));
    //添加年月点击事件
    $('.year-obj,.month-obj').click(function () {
        $('#' + $(this).parent().attr('valId')).text(this.innerHTML);
        setDay();
    });
    setDay();
}

/**
 * 设置年月日中的日
 */
function setDay() {
    let setDate = new Date($('#showYear').text(),$('#showMonth').text(),0),
    maxDay = setDate.getDate(),dayArr = [];
    for (let d = 0; d < maxDay; d ++){
        dayArr.push('<span class="choose-obj day-obj">' + d + '</span>');
    }
    $('#dayList').empty().append(dayArr.join(''));
    //添加日点击事件
    $('.day-obj').click(function () {
        $('#' + $(this).parent().attr('valId')).text(this.innerHTML);
    });
}
/**
 * 加载我的主页查看次数数据
 */
function loadHomePageLookNum() {
    $.ajax({
        type: 'post',
        url : '/ventUserIndex/countHomeAccessNum',
        dataType: 'json',
        async: false,
        timeout: 12000,
        data: {year: nowYear.substring(2,2)},
        success: function (countData) {
            if (countData.status == -1){
                return;
            }
            setHomeAccessNum(countData.data,nowYear);
        },
        error: function () {
            alert("获取统计信息失败，请稍候再试");
        }
    });
}
/**
 * 设置我的主页查看次数数据
 */
function setHomeAccessNum(homeAccessData,year) {
    let myChart = echarts.init(I('homePageLookNum'));
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(getOption(year + '年主页被访问次数',monthArr,'主页被访问次数',getCountDataArr(homeAccessData,'homeAccessNum')));
}

/**
 * 获取chart图表配置对象
 * @param titleText title.text值
 * @param xAxisData xAxis.data数据数组
 * @param seriesName series.name
 * @param seriesData series.data数据数组
 * @returns 配置对象
 */
function getOption(titleText,xAxisData,seriesName,seriesData) {
    return {
        title:{
            text: titleText,
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
                axisPointer: {
                type: 'shadow'// 默认为直线，可选为：'line' | 'shadow'
            }
        },
        xAxis: {
            name: '月',
            type: 'category',
            boundaryGap: false,
            data: xAxisData
        },
        yAxis: {
            name: '次',
            type: 'value'
        },
        series: {
                name: seriesName,
                data: seriesData,
                type: 'line',
                areaStyle: {
                color: '#28a745'
            }
        }
    };
}
/**
 * 加载访问网站次数
 */
function loadAccessSiteNum() {
    $.ajax({
        type: 'post',
        url : '/ventUserIndex/countAccessSiteNum',
        dataType: 'json',
        async: false,
        timeout: 12000,
        data: {year: nowYear.substring(2,2)},
        success: function (countData) {
            if (countData.status == -1){
                return;
            }
            setAccessSiteNum(countData.data,nowYear);
        },
        error: function () {
            alert("获取统计信息失败，请稍候再试");
        }
    });
}
function setAccessSiteNum(accessSiteData,year) {
    let myChart = echarts.init(I('accessSiteNum'));
    let o = getOption(year + '年访问本站次数',monthArr,'本站访问次数',getCountDataArr(accessSiteData,'accessSiteNum'));
    o.tooltip.axisPointer.label = {formatter: '{value} 月'};
    o.series.type = 'bar';
    o.xAxis.boundaryGap = true;
    myChart.setOption(o);
}
/**
 * 加载发布吐槽数量
 */
function loadIssueVentNum() {
    $.ajax({
        type: 'post',
        url : '/vent/countVentTotalByUser',
        dataType: 'json',
        async: false,
        timeout: 12000,
        data: {year: nowYear},
        success: function (countData) {
            if (countData.status == -1){
                return;
            }
            setVentTotal(countData.data,nowYear);
        },
        error: function () {
            alert("获取统计信息失败，请稍候再试");
        }
    });
}

/**
 * 获取统计数据数组
 * @param countData 统计的数据集
 * @param p countData中数据的统计数据对应的属性
 * @returns {number[]} 统计数据数组
 */
function getCountDataArr(countData,p) {
    let countDataArr = zeroArr;
    if (!isNull(countData)){
        for (let g = 0; g < countData.length; g ++){
            let ha = countData[g], m = ha.month;
            countDataArr[parseInt(m) - 1] = ha[p];
        }
    }
    return countDataArr;
}
/**
 * 画发布吐槽总数折线图
 * @param ventTotalData 吐槽总数数据
 * @param year 年
 */
function setVentTotal(ventTotalData,year) {
    let myChart = echarts.init(I('issueVentNum'));
    let o = getOption(year + '年发布的吐槽数',monthArr,'吐槽数',getCountDataArr(ventTotalData,'ventTotal'));
    o.tooltip.axisPointer.label = {formatter: '{value} 月'};
    o.series.type = 'line';
    o.yAxis.name = '吐槽数';
    myChart.setOption(o);
}
/**
 * 加载点赞数量
 */
function loadLikeVentNum() {
    $.ajax({
        type: 'post',
        url : '/ventLike/countLikeTotal',
        dataType: 'json',
        async: false,
        timeout: 12000,
        data: {year: nowYear},
        success: function (countData) {
            if (countData.status == -1){
                return;
            }
            setVentLikeTotal(countData.data,nowYear);
        },
        error: function () {
            alert("获取统计信息失败，请稍候再试");
        }
    });
}

/**
 * 画点赞总数柱状图
 * @param likeTotalData 点赞总数统计数据
 * @param year 年
 */
function setVentLikeTotal(likeTotalData,year) {
    let myChart = echarts.init(I('likeVentNum'));
    let option = {
        title:{
            text: year + '年吐槽被点赞数',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis'
        },
        toolbox: {
            show: true,
            feature: {
                dataView: {
                    show: true,
                    readOnly: true,
                    title: '数据视图',
                    lang: ['数据视图', '关闭', '刷新']
                },
                magicType: {
                    show: true,
                    type: ['line', 'bar'],
                    title: {
                        line:'切换为拆线图',
                        bar:'切换为柱状图'
                    }
                },
                restore: {
                    show: true,
                    title: '还原'
                },
                saveAsImage: {
                    show: true,
                    title: '保存为图片'
                }
            }
        },
        calculable: true,
        xAxis: {
            name: '月',
            type: 'category',
            data: monthArr
        },
        yAxis: {
            name: '点赞数',
            type: 'value'
        },
        series: {
            name: '点赞数',
            type: 'bar',
            data: getCountDataArr(likeTotalData,'likeTotal'),
            markPoint: {
                data: [
                    {type: 'max', name: '最大值'},
                    {type: 'min', name: '最小值'}
                ]
            },
            itemStyle: {
                color: '#28a745'
            },
            markLine: {
                data: [
                    {type: 'average', name: '平均值'}
                ]
            }
        }
    };
    myChart.setOption(option);
}
/**
 * 保存我的信息
 */
function saveMyInfo() {
    let myEmail = $('#email').val();
    if (!isNull(myEmail) && !checkEmail(myEmail)){
        errMsg('邮箱不正确');
        return;
    }
    let btnSave = $('#btnSaveMyInfo'),
    sex = $('#sex').is(':checked') ? 1 : 0,bloodType = $('#bloodType option:selected').text(),
        occupationId = $('#occupationName option:selected').val();
    bloodType = bloodType == '其它' ? 'T' : bloodType;
    let editUserInfo = {
        'nickName': V('nickName'),
        'birthday': getBirthday(),
        'sex': sex,
        'atCityCode': selectCityCode,
        'email': V('email'),
        'bloodType': bloodType,
        'occupationId': occupationId
    };
    setButtonStatus(btnSave,true,'保存中...');
	$.ajax({
		type: 'post',
		url : '/ventUserIndex/editUserInfo',
		dataType: 'json',
        async: false,
		timeout: 120000,
		data: editUserInfo,
		success: function (saveData) {
            let s = saveData.status;
            if (s == -1){
                alert('登录失效，请重新登录');
                setLogin();
                return;
            }
            if (s == 1){
                errMsg('保存出错，请稍候再试');
            }else {
                setSaveUserInfo(editUserInfo);
            }
            setButtonStatus(btnSave,false,'保存');
		},
		error: function () {
			errMsg("保存失败，请稍候再试");
			setButtonStatus(btnSave,false,'保存');
		}
	});
}
function errMsg(str) {
    $('.error-msg').text(str);
}
function getBirthday() {
    let year = $('#showYear').text(),month = $('#showMonth').text(), day = $('#showDay').text();
    if (isNull(year) || year == '年' || isNull(month) || month == '月' || isNull(day) || day == '日'){
        return '';
    }
    return year + '-' + month + '-' + day;
}
/**
 * 设置保存用户信息
 * @param editUserInfo 保存的用户对象
 */
function setSaveUserInfo(editUserInfo) {
    my = editUserInfo;
    setInfo(editUserInfo);
    $('#seeBirthday').text(editUserInfo.birthday.substring(0,2) + '**年');
    $('#seeAtCityName').text(selectCityName);
    $('#seeOccupationName').text($('#occupationName option:selected').text());
    cancelEdit();
}

/**
 * 取消编辑，隐藏输入框，显示span
 */
function cancelEdit() {
    $('header .left,header .right').css('width','auto');
    $('.btn-edit,.see,.edit-phone').show();
    $('.btn-group .btn,.edit').hide();
}
/**
 * 加载我的吐槽集合
 */
function listMyVent(currentPage,pageSize) {
    let myVent = $('#myVentList');
    //如果已加载过了，则不再加载
    if(myVent.children('.vent-obj').length > 0){
        return;
    }
    let ventHeight = myVent.height();
    $('.page-mask').css({'height': ventHeight + 'px','margin-top': -ventHeight + 'px'});
    $('#loadingWord').css('line-height',ventHeight + 'px');
    $.ajax({
        type: 'post',
        url : '/vent/pageMyVent',
        dataType: 'json',
        timeout: 12000,
        data: {
            pageNo: currentPage,
            pageSize: pageSize
        },
        success: function (myVentPi) {
            if (myVentPi.status == -1){
                alert('登录失效，请重新登录');
                return;
            }
            appendMyVentHtml(currentPage,pageSize,myVentPi);
        },
        error: function () {
            alert("吐槽信息加载失败，请稍候再试");
        }
    });
}
/**
 * 加载吐槽数据列表
 * @param currentPage 当前页号
 * @param pageSize 每页显示的订单数
 * @param pageVent 吐槽分页数据
 */
function appendMyVentHtml(currentPage, pageSize,pageVent) {
    let ventArray = pageVent.list,ventListDiv = $('#myVentList'),paginate = $('.wp-paginate');
    ventListDiv.children('.vent-obj').remove();
    $('#btnMyVent label').text(pageVent.total);
    if (ventArray != null && ventArray.length > 0) {
        //服务订单数据
        let appendArr = [],ventListSize = ventArray.length;
        for (let s = 0; s < ventListSize; s ++) {
            appendArr.push(getVentHtml(s + 1,ventArray[s],'m'));
        }
        ventListDiv.append(appendArr.join('')).show();
        //添加分页工具栏
        paginate.children().remove();
        //总记录数,总页数
        ventTotalPage = parseInt(pageVent.pages);

        let ellipsisLi = '<li class="page-ellipsis">…</li>',
            pageNums = pageVent.navigatepageNums, aHref = 'href="javascript:void(0)"';
        let firstClass = 'first-page', previousClass = 'previous-page', isHave = '';
        //如果没有上一页
        if (!pageVent.hasPreviousPage) {
            firstClass = 'no-first';
            previousClass = 'no-previous';
            isHave = 'no-have';
        }
        let appendStr = '<li title="第一页" class="' + firstClass + '"><a ' + aHref + ' class="first ' + isHave + '"></a></li>' +
            '<li title="上一页" class="' + previousClass + '"><a ' + aHref + ' class="previous ' + isHave + '"></a></li>';
        if (pageNums[0] > 1){
            appendStr += ellipsisLi;
        }
        if (ventTotalPage > 0) {
            //页面要显示的页数集合
            for (let g = 0; g < pageNums.length; g++) {
                let currentClass = pageNums[g] == currentPage ? 'current' : 'have';
                appendStr += '<li><a ' + aHref + ' class="page ' + currentClass + '">' + pageNums[g] + '</a></li>';
            }
        }
        if (pageNums[pageNums.length - 1] < pageVent.pages){
            appendStr += ellipsisLi;
        }
        let nextClass = 'next-page', lastClass = 'last-page';
        isHave = '';
        //如果没有下一页
        if (!pageVent.hasNextPage){
            nextClass = 'no-next';
            lastClass = 'no-last';
            isHave = 'no-have';
        }
        appendStr += '<li title="下一页" class="' + nextClass + '"><a ' + aHref + ' class="next ' + isHave + '"></a></li>' +
            '<li title="最后一页" class="' + lastClass + '"><a ' + aHref + ' class="last ' + isHave + '"></a></li>';
        paginate.append(appendStr);
    } else {
        ventListDiv.append('<span style="fonts-size: 18px;">您很幸运，没有需要吐槽的</span>');
    }
    //分页数字点击事件
    $(".wp-paginate a").click(function() {
        let className = this.className;
        //如果class不包含no-have，并且不是当前页
        if (className.indexOf('no-have') > -1 || parseInt(this.innerText) == currentPage) {
            return;
        }
        if (className.indexOf('first') > -1) {
            currentPage = 1;
        } else if (className.indexOf('previous') > -1) {
            currentPage = currentPage > 1 ? currentPage - 1 : 1;
        } else if (className.indexOf('next') > -1) {
            currentPage = currentPage < ventTotalPage ? currentPage + 1 : ventTotalPage;
        } else if (className.indexOf('last') > -1) {
            currentPage = ventTotalPage;
        } else {
            currentPage = parseInt(this.innerText);
        }
        ventListDiv.children('.vent-obj').remove();
        listMyVent(currentPage, pageSize);
    });
    $('.loading,.page-mask').hide();
    let contentWidth = ventListDiv.width();
    //设置内容的宽度
    $('.content').css('width', (contentWidth - 96) + 'px');
    $(".del-vent").click(function() {
        delVentById(this,$(this).attr('delId'));
    });
}

/**
 * 删除吐槽数据
 * @param delId 吐槽ID
 */
function delVentById(btnDelVent,delId) {
    if (isNull(delId) || delId < 1){
        alert('删除吐槽数据失败，请刷新页面再试');
        return;
    }
    $.ajax({
        type: 'post',
        url : '/vent/delVentById',
        dataType: 'json',
        timeout: 12000,
        data: {delVentId: delId},
        success: function (delData) {
            if (delData.status == -1){
                alert('登录失效，请重新登录');
                return;
            }
            $(btnDelVent).parent().parent().remove();
        },
        error: function () {
            alert("删除失败，请稍候再试");
        }
    });
}
//获取验证码
function goGetCheckCode() {
    let waitGetCode = '系统繁忙,请稍后再获取验证码';
    $.ajax({
        type: "POST",
        url: '/ventUserIndex/sendCodeByLogin',
        dataType: 'json',
        success: function(sendResult) {
            let rs = sendResult.status;
            if(rs != '1'){
                setGetCheckCodeEnable();
            }
            if(rs == '3'){
                alert('登录失效，请重新登录');
                sessionStorage.setItem('backUrl','myHome');
                window.location.href = 'userLogin.html';
            }else if(rs == '1'){
                epErrMsg('验证码已发送,20分钟内有效');
            }else if(rs == '4'){
                epErrMsg('您IP地址获取验证码次数过多，请稍候再试');
            }else if(rs == '5'){
                epErrMsg('您手机号获取验证码次数过多，请稍候再试');
            }else {
                epErrMsg(waitGetCode);
            }
        },
        error: function() {
            epErrMsg(waitGetCode);
            setGetCheckCodeEnable();
        }
    });
}
/**
 * 设置或许验证码按钮可用
 * @returns
 */
function setGetCheckCodeEnable() {
    window.clearInterval(checkCodeInterval);
    $('#btnGetCheckCode').val('获取验证码');
    $('#phoneErrorMsg').text('');
    I('btnGetCheckCode').disabled = false;
}
/**
 * 修改手机号码
 */
function modifyMyPhone() {
    let myNewPhone = V('myNewPhone'), checkCode = V('oldPhoneCheckCode');
    let errMsg = checkModifyMyPhone(myNewPhone,checkCode);
    if (errMsg.length > 1){
        epErrMsg(errMsg);
        I('submitNewPhone').disabled = false;
        return;
    }
    $.ajax({
        type: "POST",
        url: '/ventUserIndex/modifyMyPhone',
        dataType: 'json',
        data: {
            newPhone: myNewPhone,
            checkCode: checkCode
        },
        success: function(res) {
            I('submitNewPhone').disabled = false;
            if(res == '0'){
                let me = localStorage.getItem('me');
                me = JSON.parse(me);
                me.userPhone = myNewPhone;
                me.userName = myNewPhone;
                localStorage.setItem('me', JSON.stringify(me));
                I('oldPhoneCheckCode').value = '';
                I('myNewPhone').value = '';
                alert('手机号码修改成功');
                resetEditPhone();
                $('#seePhone').text(myNewPhone.substring(0,1) + '*******' + myNewPhone.substring(8,11));
            }else if(res == '1'){
                epErrMsg('手机号码修改时出错');
            }else if(res == '2'){
                epErrMsg('该手机号已被注册');
            }else if(res == '3'){
                epErrMsg('您登录已失效，请重新登录');
            }else if(res == '4'){
                epErrMsg('未获取验证码');
            }else if(res == '5'){
                epErrMsg('验证码失效或不正确');
            }else if(res == '6'){
                epErrMsg('未获取到手机号码');
            }else if(res == '7'){
                epErrMsg('新手机号不能跟原手机号相同');
            }else {
                epErrMsg('手机号码修改失败');
            }
        },
        error: function() {
            epErrMsg(errorTip);
            I('submitNewPhone').disabled = false;
        }
    });
}
function epErrMsg(s) {
    $('#phoneErrorMsg').text(s);
}
/**
 * 校验修改我的手机号
 * @param myNewPhone 新手机号
 * @param checkCode 验证码
 */
function checkModifyMyPhone(myNewPhone,checkCode) {
    if(isNull(checkCode)){
        return '验证码不能为空';
    }
    if(isNull(myNewPhone)){
        return '新手机号不能为空';
    }
    if(checkCode.length != 6){
        return '验证码码错误';
    }
    if(!phoneNumberIsRight(myNewPhone)){
        return '新手机号码格式不对';
    }
    let me = localStorage.getItem('me');
    me = JSON.parse(me);
    if (myNewPhone == me.userPhone){
        return '新手机号不能跟原手机号相同';
    }
    return '';
}

/**
 * 添加图片集
 */
function uploadMyImg() {
    let imgReader = new FileReader();
    let imgFile = document.getElementById('uploadImg').files[0];
    if (!/\/(?:jpeg|jpg|png)/i.test(imgFile.type)){
        showError('请选择图片再上传');
        return;
    }
    let imgFormData = new FormData(), imgPath = 'userHeaderImg/' + yearMonth;
    // 通过append向form对象添加数据
    imgFormData.append('file', imgFile);
    imgFormData.append('imgPath',imgPath);
    fileUpload(imgFormData,function (uploadImgData) {
        imgReader.readAsDataURL(imgFile);
        imgReader.onload = function (e) {
            updateMyHeaderImg(imgPath + '/' + uploadImgData.fileName,e.target.result);
        };
    },function () {
        epErrMsg(imgFile.name + '头像上传失败，请重新选择');
    });
}
/**
 * 修改手机号码
 */
function updateMyHeaderImg(imgPath,imgUrl) {
    $.ajax({
        type: "POST",
        url: '/ventUserIndex/updateHeaderImg',
        dataType: 'json',
        data: {headerImgPath: imgPath},
        success: function(res) {
            if (res.status == -1){
                alert('登录失效，请重新登录');
                return;
            }
            setMyHeaderImg(imgUrl);
        },
        error: function() {
            epErrMsg('头像上传失败，请稍候再试');
        }
    });
}